﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;


namespace YouWei.Utility
{
    /// <summary>
    /// 字符串处理类
    /// </summary>
    public static class StringHelper
    {
        #region Variables
        private static readonly Regex STRIP_HTML_REGEX = new Regex("<[^>]*>", RegexOptions.Compiled);
        #endregion



        #region 把字符串从一种编码转换到另一种编码

        /// <summary>
        /// 把字符串从一种编码转换到另一种编码
        /// </summary>
        /// <param name="fromText">需要转换的字符串</param>
        /// <param name="fromEncoding">原始编码</param>
        /// <param name="toEncoding">转换后的编码</param>
        /// <returns>转换结果</returns>
        public static string TransferEncoding(string fromText, Encoding fromEncoding, Encoding toEncoding)
        {
            byte[] fromTextBytes = fromEncoding.GetBytes(fromText);
            byte[] rstAsciiBytes = Encoding.Convert(fromEncoding, toEncoding, fromTextBytes);
            char[] rstAsciiChars = new char[toEncoding.GetCharCount(rstAsciiBytes, 0, rstAsciiBytes.Length)];
            toEncoding.GetChars(rstAsciiBytes, 0, rstAsciiBytes.Length, rstAsciiChars, 0);
            string rst = new string(rstAsciiChars);
            return rst;
        }
        #endregion

        #region 将base64位编码字符串转化为指定编码格式的文本

        /// <summary>
        /// 将base64位编码字符串转化为指定编码格式的文本
        /// </summary>
        /// <param name="Input">要转化为的64位编码字符串</param>
        /// <param name="EncodingUsing">指定编码格式</param>
        /// <returns>指定格式的字符串</returns>
        //public static string FromBase64(this string Input, Encoding EncodingUsing)
        //{
        //    if (string.IsNullOrEmpty(Input))
        //        return "";
        //    byte[] TempArray = Convert.FromBase64String(Input);
        //    return EncodingUsing.NullCheck(new UTF8Encoding()).GetString(TempArray);
        //}

        /// <summary>
        /// 将base64位编码转化为一个字节数组
        /// </summary>
        /// <param name="Input">base64编码字符串</param>
        /// <returns>字节数组</returns>
        public static byte[] FromBase64(this string Input)
        {
            return string.IsNullOrEmpty(Input) ? new byte[0] : Convert.FromBase64String(Input);
        }

        #endregion

        #region 将字符串以某种编码格式转化为base64位编码形式

        /// <summary>
        /// 将字符串以某种编码格式转化为base64位编码形式
        /// </summary>
        /// <param name="Input">输入</param>
        /// <param name="OriginalEncodingUsing">输入字符串的文本编码格式，默认为UTF-8</param>
        /// <returns>base64编码字符串</returns>
        //public static string ToBase64(this string Input, Encoding OriginalEncodingUsing = null)
        //{
        //    if (string.IsNullOrEmpty(Input))
        //        return "";
        //    byte[] TempArray = OriginalEncodingUsing.NullCheck(new UTF8Encoding()).GetBytes(Input);
        //    return Convert.ToBase64String(TempArray);
        //}

        #endregion

        #region 获取字符串左边起指定个数的子字符串

        /// <summary>
        /// 获取字符串左边起指定个数的子字符串
        /// </summary>
        /// <param name="Input">要获取其左边指定个数子字符串的源字符串</param>
        /// <param name="Length">指定个数</param>
        /// <returns></returns>
        public static string Left(this string Input, int Length)
        {
            return string.IsNullOrEmpty(Input) ? "" : Input.Substring(0, Input.Length > Length ? Length : Input.Length);
        }

        #endregion

        #region 获取字符串右边起指定个数的子字符串

        /// <summary>
        /// 获取字符串右边起指定个数的子字符串
        /// </summary>
        /// <param name="Input">要获取其右边指定个数子字符串的源字符串</param>
        /// <param name="Length">要获取其左边指定个数子字符串的源字符串</param>
        /// <returns></returns>
        public static string Right(this string Input, int Length)
        {
            if (string.IsNullOrEmpty(Input))
                return "";
            Length = Input.Length > Length ? Length : Input.Length;
            return Input.Substring(Input.Length - Length, Length);
        }

        #endregion



        #region 将字符串转化为字节数组

        /// <summary>
        /// 将字符串转化为字节数组
        /// </summary>
        /// <param name="Input">要转化为字节数组的字符串</param>
        /// <param name="EncodingUsing">使用的编码格式，默认为UTF-8</param>
        /// <returns>字节数组</returns>
        //public static byte[] ToByteArray(this string Input, Encoding EncodingUsing = null)
        //{
        //    return string.IsNullOrEmpty(Input) ? null : EncodingUsing.NullCheck(new UTF8Encoding()).GetBytes(Input);
        //}

        #endregion

        #region 句首字符转大写

        /// <summary>
        /// 句首字符转大写
        /// </summary>
        /// <param name="Input">字符串输入</param>
        /// <returns>以大写字母开关的字符串</returns>
        public static string ToFirstCharacterUpperCase(this string Input)
        {
            if (string.IsNullOrEmpty(Input))
                return "";
            char[] InputChars = Input.ToCharArray();
            for (int x = 0; x < InputChars.Length; ++x)
            {
                if (InputChars[x] != ' ' && InputChars[x] != '\t')
                {
                    InputChars[x] = char.ToUpper(InputChars[x]);
                    break;
                }
            }
            return new string(InputChars);
        }

        #endregion

        #region 将字符串以分隔符数组作为拆分依据划分成多个句子，并将每个句子首字符大写

        /// <summary>
        /// 将字符串以{ ".", "?", "!" }作为拆分依据划分成多个句子，并将每个句子首字符大写
        /// </summary>
        /// <param name="Input">Input string</param>
        /// <returns>String with each sentence capitalized</returns>
        public static string ToSentenceCapitalize(this string Input)
        {
           return ToSentenceCapitalize(Input,new []{ ".", "?", "!" });
        }
        /// <summary>
        /// 将字符串以分隔符数组作为拆分依据划分成多个句子，并将每个句子首字符大写
        /// </summary>
        /// <param name="Input">要拆分的文本</param>
        /// <param name="arrSeperator">分隔符数组，如{ ".", "?", "!" }</param>
        /// <returns></returns>
        public static string ToSentenceCapitalize(this string Input,string[] arrSeperator)
        {
            if (string.IsNullOrEmpty(Input))
                return "";
            //string[] Seperator = { ".", "?", "!" };
            string[] InputStrings = Input.Split(arrSeperator, StringSplitOptions.None);
            for (int x = 0; x < InputStrings.Length; ++x)
            {
                if (!string.IsNullOrEmpty(InputStrings[x]))
                {
                    Regex TempRegex = new Regex(InputStrings[x]);
                    InputStrings[x] = InputStrings[x].ToFirstCharacterUpperCase();
                    Input = TempRegex.Replace(Input, InputStrings[x]);
                }
            }
            return Input;
        }

        #endregion

        #region 将字符串每个单词的首字母大写

        /// <summary>
        ///将字符串每个单词的首字母大写
        /// </summary>
        /// <param name="Input">Input string</param>
        /// <returns>String with each word capitalized</returns>
        public static string ToTitleCase(this string Input)
        {
            if (string.IsNullOrEmpty(Input))
                return "";
            string[] Seperator = { " ", ".", "\t", Environment.NewLine, "!", "?" };
            string[] InputStrings = Input.Split(Seperator, StringSplitOptions.None);
            for (int x = 0; x < InputStrings.Length; ++x)
            {
                if (!string.IsNullOrEmpty(InputStrings[x])
                    && InputStrings[x].Length > 3)
                {
                    Regex TempRegex = new Regex(InputStrings[x]);
                    InputStrings[x] = InputStrings[x].ToFirstCharacterUpperCase();
                    Input = TempRegex.Replace(Input, InputStrings[x]);
                }
            }
            return Input;
        }

        #endregion

        #region 获取一个子字符串在一个字符串中出现的次数

        /// <summary>
        ///获取一个子字符串在一个字符串中出现的次数
        /// </summary>
        /// <param name="Input">要检查子字符串出现次数的源字符串</param>
        /// <param name="Match">子字符串，也可是正则表达式</param>
        /// <returns>子字符串出现的次数</returns>
        public static int NumberTimesOccurs(this string Input, string Match)
        {
            return string.IsNullOrEmpty(Input) ? 0 : new Regex(Match).Matches(Input).Count;
        }

        #endregion

        #region 字符串倒置

        /// <summary>
        /// 字符串倒置
        /// </summary>
        /// <param name="Input">要倒置的字符串</param>
        /// <returns></returns>
        public static string Reverse(this string Input)
        {
            return new string(Input.Reverse<char>().ToArray());
        }

        #endregion

        #region FilterOutText

        /// <summary>
        /// Removes the filter text from the input.
        /// </summary>
        /// <param name="Input">Input text</param>
        /// <param name="Filter">Regex expression of text to filter out</param>
        /// <returns>The input text minus the filter text.</returns>
        public static string FilterOutText(this string Input, string Filter)
        {
            if (string.IsNullOrEmpty(Input))
                return "";
            return string.IsNullOrEmpty(Filter) ? Input : new Regex(Filter).Replace(Input, "");
        }

        #endregion

        #region 去除文本中不符合过滤格式的字符，只保留符合过滤格式的字符

        /// <summary>
        /// 去除文本中不符合过滤格式的字符，只保留符合过滤格式的字符
        /// </summary>
        /// <param name="Input">输入文本</param>
        /// <param name="Filter">需要保留的字符串格式，一个正则表达式</param>
        /// <returns></returns>
        public static string KeepFilterText(this string Input, string Filter)
        {
            if (string.IsNullOrEmpty(Input) || string.IsNullOrEmpty(Filter))
                return "";
            Regex TempRegex = new Regex(Filter);
            MatchCollection Collection = TempRegex.Matches(Input);
            StringBuilder Builder = new StringBuilder();
            foreach (Match Match in Collection)
                Builder.Append(Match.Value);
            return Builder.ToString();
        }

        #endregion

        #region 只保留文本中的字母（大小写）、数字字符，去除所有其他字符

        /// <summary>
        /// 只保留文本中的字母（大小写）、数字字符，去除所有其他字符
        /// </summary>
        /// <param name="Input">输入文本</param>
        /// <returns></returns>
        public static string AlphaNumericOnly(this string Input)
        {
            return Input.KeepFilterText("[a-zA-Z0-9]");
        }

        #endregion

        #region 只保留文本中的字母(大小写)字符

        /// <summary>
        /// 只保留文本中的字母(大小写)字符
        /// </summary>
        /// <param name="Input">输入文本</param>
        /// <returns></returns>
        public static string AlphaCharactersOnly(this string Input)
        {
            return Input.KeepFilterText("[a-zA-Z]");
        }

        #endregion

        #region 去除文本中非数字字符【0-9】

        /// <summary>
        /// 去除文本中非数字字符【0-9】
        /// </summary>
        /// <param name="Input">输入文本</param>
        /// <param name="KeepNumericPunctuation">是否需要保留小数点【.】,默认为true</param>
        /// <returns></returns>
        public static string NumericOnly(this string Input, bool KeepNumericPunctuation = true)
        {
            return KeepNumericPunctuation ? Input.KeepFilterText(@"[0-9\.]") : Input.KeepFilterText("[0-9]");
        }

        #endregion

        #region 检查文本是否为Unicode格式编码

        /// <summary>
        /// 检查文本是否为Unicode格式编码
        /// </summary>
        /// <param name="Input">要检查的文本</param>
        /// <returns>如果是Unicode则返回true,否则返回false</returns>
        public static bool IsUnicode(this string Input)
        {
            return string.IsNullOrEmpty(Input) || Regex.Replace(Input, @"[^\u0000-\u007F]", "") != Input;
        }

        #endregion

        

        #region RegexFormat

        /// <summary>
        /// 用一个正则表达式来格式化字符串，即将满足正则格式的字符串(Format)替换为指定的替换字符串(OutputFormat)
        /// </summary>
        /// <param name="Input">要改变的字符串</param>
        /// <param name="Format">正则格式字符串</param>
        /// <param name="OutputFormat">替换字符串</param>
        /// <param name="Options">正达表达式选项</param>
        /// <returns>格式化后的字符串</returns>
        //public static string RegexFormat(this string Input, string Format, string OutputFormat, RegexOptions Options = RegexOptions.None)
        //{
        //    Input.ThrowIfNullOrEmpty("Input");
        //    return Regex.Replace(Input, Format, OutputFormat, Options);
        //}

        #endregion

        #region 转换
        /// <summary>
        /// 全角转半角
        /// </summary>
        /// <param name="input">要转换的字符串</param>
        /// <returns>转换完的字符串</returns>
        //public static string Narrow(this string input)
        //{
        //    return Strings.StrConv(input, VbStrConv.Narrow);
        //}
        /// <summary>
        /// 半角转全角
        /// </summary>
        /// <param name="input">要转换的字符串</param>
        /// <returns>转换完的字符串</returns>
        //public static string Wide(this string input)
        //{
        //    return Strings.StrConv(input, VbStrConv.Wide);
        //}
        /// <summary>
        /// 简体转繁体
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //public static string TraditionalChinese(this string input)
        //{
        //    return Strings.StrConv(input, VbStrConv.TraditionalChinese);
        //}
        /// <summary>
        /// 繁体转简体
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //public static string SimplifiedChinese(this string input)
        //{
        //    return Strings.StrConv(input, VbStrConv.SimplifiedChinese);
        //}
        /// <summary>
        /// 将每个单词首字母大写
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //public static string ProperCase(this string input)
        //{
        //    return Strings.StrConv(input, VbStrConv.ProperCase);
        //}
        #endregion


        #region 检查字符串是否包含Html内容即Html标签

        /// <summary>
        /// 检查字符串是否包含Html内容即Html标签，如<b>**</b>,<body>**</body>等 
        /// </summary>
        /// <param name="Input">要检查的字符串</param>
        /// <returns>包含则返回true,否则返回false</returns>
        public static bool ContainsHTML(this string Input)
        {
            return !string.IsNullOrEmpty(Input) && STRIP_HTML_REGEX.IsMatch(Input);
        }



        #endregion

        #region 去除字符串不合法的Url字符，如【:/?#[]@.\&'空格等字符】

        /// <summary>
        /// 去除字符串不合法的Url字符
        /// </summary>
        /// <param name="Input">要去除不合法Url字符的字符串</param>
        /// <returns></returns>
        public static string RemoveURLIllegalCharacters(this string Input)
        {
            if (string.IsNullOrEmpty(Input))
                return "";
            Input = Input.Replace(":", string.Empty)
                        .Replace("/", string.Empty)
                        .Replace("?", string.Empty)
                        .Replace("#", string.Empty)
                        .Replace("[", string.Empty)
                        .Replace("]", string.Empty)
                        .Replace("@", string.Empty)
                        .Replace(".", string.Empty)
                        .Replace("\"", string.Empty)
                        .Replace("&", string.Empty)
                        .Replace("'", string.Empty)
                        .Replace(" ", "-");
            Input = RemoveExtraHyphen(Input);
            Input = RemoveDiacritics(Input);
            return HttpUtility.UrlEncode(Input).Replace("%", string.Empty);
        }



        #endregion

        #region StripHTML

        /// <summary>
        /// 从一段HTML文本中清除HTML标签，包括Html实体表示法的空格字符如：&nbsp;&#160等
        /// </summary>
        /// <param name="HTML">要去除HTML标记的文本</param>
        /// <returns>纯文本</returns>
        public static string StripHTML(this string HTML)
        {
            if (string.IsNullOrEmpty(HTML))
                return "";
            HTML = STRIP_HTML_REGEX.Replace(HTML, string.Empty);
            return HTML.Replace("&nbsp;", " ")
                       .Replace("&#160;", string.Empty);
        }



        #endregion


        #region HTML转换为文本
        /// <summary>
        ///从一段HTML文本中清除HTML标签
        /// </summary>
        /// <param name="html">要去除HTML标记的文本</param>
        /// <returns>结果</returns>
        public static string ParseHtml(this string html)
        {
            if (string.IsNullOrEmpty(html))
                return string.Empty;
            return Regex.Replace(html, "<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 去除文本中指定的HTML标记
        /// </summary>
        /// <param name="html">要去除HTML标记的文本</param>
        /// <param name="tag">指定HTML标记</param>
        /// <returns>结果</returns>
        public static string ParseHtml(this string html, string tag)
        {
            if (string.IsNullOrEmpty(html))
                return string.Empty;
            return Regex.Replace(html, @"<[/" + tag + @"\s/]*>", string.Empty);
        }
        #endregion

        #region 统计字数（忽略HTML标记）
        /// <summary>
        /// 统计字数（忽略HTML标记，也包括实体空格;全角空格，半角空格）
        /// </summary>
        /// <param name="inputHtml">要统计的字符串</param>
        /// <returns></returns>
        public static int WordCountExceptHtml(this string inputHtml)
        {
            if (string.IsNullOrEmpty(inputHtml))
                return 0;
            string text = inputHtml.StripHTML();
            return text.Replace("&nbsp;", " ").Replace("　", " ").Trim().Length;
        }
        #endregion

        #region 判断http地址是否存在
        /// <summary>
        /// 判断http地址是否存在
        /// </summary>
        /// <param name="Url">要检查的Url字符串</param>
        /// <returns></returns>
        public static bool IsUrlExists(this string Url)
        {
            try
            {
                System.Net.HttpWebRequest myRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Url);
                myRequest.Method = "HEAD";
                myRequest.Timeout = 2000;
                System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)myRequest.GetResponse();
                return (res.StatusCode == System.Net.HttpStatusCode.OK);
            }
            catch
            {
                //System.Diagnostics.Trace.Write(we.Message);
                return false;
            }
        }

        #endregion
       
       



        #region 获取字符串的实际字节长度的方法
        /// <summary>
        /// 获取字符串的实际字节长度的方法
        /// </summary>
        /// <param name="source">字符串</param>
        /// <returns>实际长度</returns>
        public static int GetRealLength(this string source)
        {
            return Encoding.Default.GetByteCount(source);
        }
        #endregion

      

        #region 过滤脚本攻击:sql注入,跨站脚本,flash嵌入

        /// <summary>
        /// 过滤字符串中注入SQL脚本的方法
        /// </summary>
        /// <param name="source">传入的字符串</param>
        /// <returns>过滤后的字符串</returns>
        public static string SqlFilter(this string source)
        {
            //半角括号替换为全角括号
            source = source.Replace("'", "''").Replace(";", "；").Replace("(", "（").Replace(")", "）");

            //去除执行SQL语句的命令关键字
            source = Regex.Replace(source, "select", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "insert", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "update", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "delete", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "drop", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "truncate", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "declare", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "xp_cmdshell", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "/add", "", RegexOptions.IgnoreCase);
            //Regex.Replace(source, "asc(", "", RegexOptions.IgnoreCase);
            //Regex.Replace(source, "mid(", "", RegexOptions.IgnoreCase);
            //Regex.Replace(source, "char(", "", RegexOptions.IgnoreCase);
            //Regex.Replace(source, "count(", "", RegexOptions.IgnoreCase);
            //fetch 
            //IS_SRVROLEMEMBER
            //Cast(

            source = Regex.Replace(source, "net user", "", RegexOptions.IgnoreCase);

            //去除执行存储过程的命令关键字 
            source = Regex.Replace(source, "exec", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "execute", "", RegexOptions.IgnoreCase);

            //去除系统存储过程或扩展存储过程关键字
            source = Regex.Replace(source, "xp_", "x p_", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "sp_", "s p_", RegexOptions.IgnoreCase);

            //防止16进制注入
            source = Regex.Replace(source, "0x", "0 x", RegexOptions.IgnoreCase);

            return source;
        }

        /// <summary>
        /// 过滤字符串中的注入跨站脚本(先进行UrlDecode再过滤脚本关键字)
        /// 过滤脚本如:<script>window.alert("test");</script>输出window.alert("test");
        /// 如<a href = "javascript:onclick='fun1();'"/>输出<a href=" onXXX='fun1();'"/>
        /// 过滤掉javascript和 onXXX
        /// </summary>
        /// <param name="source">需要过滤的字符串</param>
        /// <returns>过滤后的字符串</returns>
        public static string XSSFilter(this string source)
        {
            if (source == "") return source;

            string result = HttpUtility.UrlDecode(source);

            const string replaceEventStr = " onXXX =";
            string tmpStr = "";

            string patternGeneral = @"<[^<>]*>";                              //例如 <abcd>
            string patternEvent = @"([\s]|[:])+[o]{1}[n]{1}\w*\s*={1}";
            string patternScriptBegin = @"\s*((javascript)|(vbscript))\s*[:]?";  // javascript或vbscript:
            string patternScriptEnd = @"<([\s/])*script.*>";                       // </script>   
            string patternTag = @"<([\s/])*\S.+>";                       // 例如</textarea>

            Regex regexGeneral = new Regex(patternGeneral, RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex regexEvent = new Regex(patternEvent, RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex regexScriptEnd = new Regex(patternScriptEnd, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex regexScriptBegin = new Regex(patternScriptBegin, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex regexTag = new Regex(patternTag, RegexOptions.Compiled | RegexOptions.IgnoreCase);


            Match matchGeneral, matchEvent, matchScriptEnd, matchScriptBegin, matchTag;

            //符合类似 <abcd> 条件的
            #region 符合类似 <abcd> 条件的
            //过滤字符串中的 </script>   
            for (matchGeneral = regexGeneral.Match(result); matchGeneral.Success; matchGeneral = matchGeneral.NextMatch())
            {
                tmpStr = matchGeneral.Groups[0].Value;
                matchScriptEnd = regexScriptEnd.Match(tmpStr);
                if (matchScriptEnd.Success)
                {
                    tmpStr = regexScriptEnd.Replace(tmpStr, " ");
                    result = result.Replace(matchGeneral.Groups[0].Value, tmpStr);
                }
            }

            //过滤字符串中的脚本事件
            for (matchGeneral = regexGeneral.Match(result); matchGeneral.Success; matchGeneral = matchGeneral.NextMatch())
            {
                tmpStr = matchGeneral.Groups[0].Value;
                matchEvent = regexEvent.Match(tmpStr);
                if (matchEvent.Success)
                {
                    tmpStr = regexEvent.Replace(tmpStr, replaceEventStr);
                    result = result.Replace(matchGeneral.Groups[0].Value, tmpStr);
                }
            }

            //过滤字符串中的 javascript或vbscript:
            for (matchGeneral = regexGeneral.Match(result); matchGeneral.Success; matchGeneral = matchGeneral.NextMatch())
            {
                tmpStr = matchGeneral.Groups[0].Value;
                matchScriptBegin = regexScriptBegin.Match(tmpStr);
                if (matchScriptBegin.Success)
                {
                    tmpStr = regexScriptBegin.Replace(tmpStr, " ");
                    result = result.Replace(matchGeneral.Groups[0].Value, tmpStr);
                }
            }

            #endregion

            //过滤字符串中的事件 例如 onclick --> onXXX
            for (matchEvent = regexEvent.Match(result); matchEvent.Success; matchEvent = matchEvent.NextMatch())
            {
                tmpStr = matchEvent.Groups[0].Value;
                tmpStr = regexEvent.Replace(tmpStr, replaceEventStr);
                result = result.Replace(matchEvent.Groups[0].Value, tmpStr);
            }

            //过滤掉html标签，类似</textarea>
            for (matchTag = regexTag.Match(result); matchTag.Success; matchTag = matchTag.NextMatch())
            {
                tmpStr = matchTag.Groups[0].Value;
                tmpStr = regexTag.Replace(tmpStr, "");
                result = result.Replace(matchTag.Groups[0].Value, tmpStr);
            }


            return result;
        }

        /// <summary>
        /// 过滤字符串中注入Flash代码
        /// </summary>
        /// <param name="htmlCode">输入字符串</param>
        /// <returns>过滤后的字符串</returns>
        public static string FlashFilter(this string htmlCode)
        {
            string pattern = @"\w*<OBJECT\s+.*(macromedia)[\s*|\S*]{1,1300}</OBJECT>";

            return Regex.Replace(htmlCode, pattern, "", RegexOptions.Multiline);
        }

        #endregion

       


        #region 去除价格小数点后末尾“0”的方法
        /// <summary>
        /// 去除价格小数点后末尾“0”的方法,如"15.0",处理后结果为:"15"
        /// </summary>
        /// <param name="price">去“0”之前的价格字符串</param>
        /// <returns>去“0”之后的价格字符串</returns>
        public static string TrimEndZeroForPrice(this string price)
        {
            while (price.EndsWith("0") && price.IndexOf(".") > 0)
            {
                price = price.TrimEnd('0');
            }
            if (price.EndsWith("."))
            {
                price = price.Substring(0, price.Length - 1);
            }
            return price;
        }
        #endregion

        #region 把浮点类型格式化为百分比字符串
        /// <summary>
        /// 把浮点类型格式化为百分比字符串,如：0.23，处理后返回为:"23%"，1.889=>"1.89%"
        /// </summary>
        /// <param name="num">浮点类型数据</param>
        /// <returns>百分比字符串</returns>
        public static string FormatDoubleToPercent(double num)
        {
            return (num * 100).ToString("#0.00") + "%";
        }
        #endregion

        #region 比较两个字符串的相似性

        /// <summary>
        /// 比较两个字符串的相似性，采用编辑距离（Levenshtein Distance）算法。
        /// 顾名思义，即：修改strA到strB需要的编辑次数。
        /// 参见：http://www.codeproject.com/KB/recipes/Levenshtein.aspx
        ///             http://blog.sina.com.cn/s/blog_53e1c1230100bpe1.html
        /// </summary>
        /// <param name="strA">字符串A</param>
        /// <param name="strB">字符串B</param>
        /// <returns>返回((100 * 编辑次数) / Max(strALen, strBLen))，100代表完全相似，值越小，代表相似度越小。</returns>
        public static int ComputeSimilarity(String strA, String strB)
        {
            if (strA == null)
            {
                strA = string.Empty;
            }
            if (strB == null)
            {
                strB = string.Empty;
            }

            int max = System.Math.Max(strA.Length, strB.Length);
            if (max == 0)
            {
                return 100;
            }
            return ((100 * ComputeEditTimes(strA, strB)) / max);
        }

        /// <summary>
        /// 计算编辑次数，采用编辑距离（Levenshtein Distance）算法。
        /// 顾名思义，即：修改strA到strB需要的编辑次数。
        /// 参见：http://www.codeproject.com/KB/recipes/Levenshtein.aspx
        ///             http://blog.sina.com.cn/s/blog_53e1c1230100bpe1.html
        /// </summary>
        /// <param name="strA">字符串A</param>
        /// <param name="strB">字符串B</param>
        /// <returns>返回修改strA到strB需要的编辑次数。</returns>
        public static int ComputeEditTimes(String strA, String strB)
        {
            if (strA == null)
            {
                strA = string.Empty;
            }
            if (strB == null)
            {
                strB = string.Empty;
            }

            int rowLen = strA.Length;  // length of strA
            int colLen = strB.Length;  // length of strB
            int rowIdx;                // iterates through strA
            int colIdx;                // iterates through strB
            char row_i;                // ith character of strA
            char col_j;                // jth character of strB
            int cost;                   // cost

            // Test string length
            if (Math.Max(strA.Length, strB.Length) > Math.Pow(2, 31))
                throw (new Exception("\nMaximum string length in Levenshtein.iLD is " + Math.Pow(2, 31) + ".\nYours is " + Math.Max(strA.Length, strB.Length) + "."));

            // Step 1

            if (rowLen == 0)
            {
                return colLen;
            }

            if (colLen == 0)
            {
                return rowLen;
            }

            // Create the two vectors
            int[] v0 = new int[rowLen + 1];
            int[] v1 = new int[rowLen + 1];
            int[] vTmp;



            // Step 2
            // Initialize the first vector
            for (rowIdx = 1; rowIdx <= rowLen; rowIdx++)
            {
                v0[rowIdx] = rowIdx;
            }

            // Step 3

            // Fore each column
            for (colIdx = 1; colIdx <= colLen; colIdx++)
            {
                // Set the 0'th element to the column number
                v1[0] = colIdx;

                col_j = strB[colIdx - 1];


                // Step 4

                // Fore each row
                for (rowIdx = 1; rowIdx <= rowLen; rowIdx++)
                {
                    row_i = strA[rowIdx - 1];


                    // Step 5

                    if (row_i == col_j)
                    {
                        cost = 0;
                    }
                    else
                    {
                        cost = 1;
                    }

                    // Step 6

                    // Find minimum
                    int m_min = v0[rowIdx] + 1;
                    int b = v1[rowIdx - 1] + 1;
                    int c = v0[rowIdx - 1] + cost;

                    if (b < m_min)
                    {
                        m_min = b;
                    }
                    if (c < m_min)
                    {
                        m_min = c;
                    }

                    v1[rowIdx] = m_min;
                }

                // Swap the vectors
                vTmp = v0;
                v0 = v1;
                v1 = vTmp;

            }


            // Step 7
            // Value between 0 - 100
            // 0==perfect match 100==totaly different
            // 
            // The vectors where swaped one last time at the end of the last loop,
            // that is why the result is now in v0 rather than in v1
            //System.Console.WriteLine("iDist=" + v0[rowLen]);
            //int max = System.Math.Max(rowLen, colLen);
            return v0[rowLen];
        }

        #endregion

        #region url相关
        /// <summary>
        /// 
        /// </summary>
        /// <param name="szUrl"></param>
        /// <param name="szParam"></param>
        /// <param name="szParamValue"></param>
        /// <returns></returns>
        public static string AddUrlParam(string szUrl, string szParam, string szParamValue)
        {
            string szReturn = szUrl;
            string szPrefix = "?";
            if (szUrl.Contains("?"))
            {
                szPrefix = "&";
            }
            szReturn = szUrl + szPrefix + szParam + "=" + szParamValue;
            return szReturn;
        }

        #endregion

        #region Private Functions

        /// <summary>
        /// Removes extra hyphens from a string
        /// </summary>
        /// <param name="Input">string to be stripped</param>
        /// <returns>Stripped string</returns>
        private static string RemoveExtraHyphen(string Input)
        {
            while (Input.Contains("--"))
                Input = Input.Replace("--", "-");
            return Input;
        }

        /// <summary>
        /// Removes special characters (Diacritics) from the string
        /// </summary>
        /// <param name="Input">String to strip</param>
        /// <returns>Stripped string</returns>
        private static string RemoveDiacritics(string Input)
        {
            string Normalized = Input.Normalize(NormalizationForm.FormD);
            StringBuilder Builder = new StringBuilder();
            for (int i = 0; i < Normalized.Length; i++)
            {
                Char TempChar = Normalized[i];
                if (CharUnicodeInfo.GetUnicodeCategory(TempChar) != UnicodeCategory.NonSpacingMark)
                    Builder.Append(TempChar);
            }
            return Builder.ToString();
        }



        #region 字符串其他方法

        /// <summary>
        /// 检查字符串是否为空，不为空则将szNot附到o.String()最后再返回，空则什么也不做即返回空
        /// </summary>
        /// <param name="o">转换对象</param>
        /// <param name="szNot">不为空时附加的字符串</param>
        /// <returns></returns>
        public static string NotNullOrEmptyThenAppend(object o, string szNot)
        {
            string szReturn = string.Empty;
            string szValue = o.ToString();
            if (!string.IsNullOrEmpty(szValue))
            {
                szReturn += szValue + szNot;
            }
            return szReturn;
        }
        /// <summary>
        /// 检查字符串是否为空，不为空则将szNot附到最后，空则返回szYes
        /// </summary>
        /// <param name="o">转换对象</param>
        /// <param name="szNot">不为空时附加的字符串</param>
        /// <param name="szYes">为空时返回该值</param>
        /// <returns></returns>
        public static string NotNullOrEmptyThenAppend(object o, string szNot, string szYes)
        {
            string szReturn = string.Empty;
            string szValue = o.ToString();
            if (!string.IsNullOrEmpty(szValue))
            {
                szReturn += szValue + szNot;
            }
            else
            {
                szReturn = szYes;
            }
            return szReturn;
        }

        #endregion

        #endregion


        ///   <summary>   
        ///    去除HTML标记   
        ///   </summary>   
        ///   <param    name="NoHTML">包括HTML的源码   </param>   
        ///   <returns>已经去除后的文字</returns>   
        public static string NoHTML(this string Htmlstring)
        {
           
            //删除脚本   
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML   
           
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

            return Htmlstring;
        }




        #region    移除HTML标签   
        ///   <summary>   
        ///    移除HTML标签   
        ///   </summary>   
        ///   <param    name="HTMLStr">HTMLStr</param>   
        public static string ParseTags(this string HTMLStr)
        {
            return System.Text.RegularExpressions.Regex.Replace(HTMLStr, "<[^>]*>", "");
        }

        #endregion

        #region    取出文本中的图片地址   
        ///   <summary>   
        ///    取出文本中的图片地址   
        ///   </summary>   
        ///   <param    name="HTMLStr">HTMLStr</param>   
        public static string GetImgUrl( this string HTMLStr)
        {
            string str = string.Empty;
            Regex r = new Regex(@"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>",
                    RegexOptions.Compiled);
            Match m = r.Match(HTMLStr.ToLower());
            if (m.Success)
                str = m.Result("${url}");
            return str;
        }

        #endregion

        #region IO操作
        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="path"></param>
        public static void CreateDirectory(this string path)
        {
            Directory.CreateDirectory(path);
        }
        /// <summary>
        /// 在指定文件写入文本
        /// </summary>
        /// <param name="path"></param>
        /// <param name="contents"></param>
        public static void WriteText(this string path, string contents)
        {
            File.WriteAllText(path, contents);
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path"></param>
        public static void DeleteFile(this string path)
        {
            if (File.Exists(path)) File.Delete(path);
        }
        #endregion

        #region 执行Dos操作
        /// <summary>
        /// string output1 = "del c:\\t1.txt".ExecuteDOS();
        ///string output2 = "dir".ExecuteDOS();
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public static string ExecuteDOS(this string cmd, out string error)
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            process.StandardInput.WriteLine(cmd);
            process.StandardInput.WriteLine("exit");
            error = process.StandardError.ReadToEnd();
            return process.StandardOutput.ReadToEnd();
        }
        #endregion

        /// <summary>
        /// 去除小数点后的多余的0，如：58.00，58.00000=>58
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static string TrimFloatZeroPrice(this string number)
        {
            string szReturn = string.Empty;
            string[] arr = number.Split('.');
            if (arr.Length == 2)
            {
                if (EConvert.ToInt(arr[1], 0) == 0)
                {
                    szReturn = arr[0];
                }
                else
                {
                    szReturn = number;
                }
            }
            return szReturn;
        }
        /// <summary>
        /// 美化数字类型的字符串，使“0”显示为空
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static string PreetyNumberString(this string number)
        {
            string szReturn = number;
            if (number == "0")
            {
                szReturn = string.Empty;
            }
            return szReturn;
        }
        /// <summary>
        /// 将对象进行Url编码
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ToUrlEncode(this string o)
        {
            if (o != null)
            {
                return HttpUtility.UrlEncode(o);
            }
            return "";
        }
    }



}
